from utils.aliyunsdk import aliyunsms
from django.shortcuts import render, redirect, reverse

# Create your views here.
from django.contrib.auth import login, logout, authenticate
from django.views.decorators.http import require_POST
from .forms import LoginForm, RegisterForm
from django.http import JsonResponse, HttpResponse
from utils import restful
from utils.captcha.xfzcaptcha import Captcha
from io import BytesIO
from django.contrib.auth import get_user_model
from django.core.cache import cache
User = get_user_model()


@require_POST
def login_view(request):
    form = LoginForm(request.POST)
    if form.is_valid():
        telephone = form.cleaned_data.get('telephone')
        password = form.cleaned_data.get('password')
        remember = form.cleaned_data.get('remember')
        user = authenticate(request, username=telephone, password=password)
        if user:
            if user.is_active:
                login(request, user)
                if remember:
                    request.session.set_expiry(None)
                else:
                    request.session.set_expiry(0)

                return restful.ok()
            else:

                return restful.unauth_error('您的账号已经被冻结')
                # JsonResponse( {"code": 405, 'message': '您的账号已经被冻结了', 'data': ""}, json_dumps_params = {'ensure_ascii': False})
        else:
            return restful.params_error('手机号或者密码错误')

            #JsonResponse(                {"code": 400, 'message': '手机号或者密码错误', 'data': ""}, json_dumps_params={'ensure_ascii': False})
    else:
        return restful.params_error(form.get_errors())

        #  JsonResponse(
        #     {"code": 400, 'message': '表单車验证错误', 'data': form.get_errors()}, json_dumps_params={'ensure_ascii': False})


def logout_view(request):
    logout(request)
    return redirect(reverse('index'))


@require_POST
def register(request):
    form = RegisterForm(request.POST)
    if form.is_valid():
        telephone = form.cleaned_data.get('telephone')
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password1')
        user = User.objects.create_user(
            telephone=telephone, username=username, password=password)
        login(request, user)
        return restful.ok()

    else:
        restful.params_error(message=form.get_errors())


def img_captcha(request):
    text, image = Captcha.gene_code()
    out = BytesIO()
    image.save(out, 'png')
    out.seek(0)
    response = HttpResponse(content_type='image/png')
    response.write(out.read())
    response['Content-Length'] = out.tell()
    cache.set(text.lower(), text.lower(), 5*60)
    print('图形验证码：', text)
    return response


def sms_captcha(request):
    telephone = request.GET.get('telephone')
    text = Captcha.gene_text()
    cache.set(telephone, text.lower(), 5 * 60)
    print('短信验证码：', text, telephone)
    # result = aliyunsms.send_sms(telephone, text)
    return restful.ok()
